package com.qingxun.core.system.web;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.qingxun.core.common.utils.ResultMsg;
import com.qingxun.core.system.entity.SysConfig;
import com.qingxun.core.system.entity.User;
import com.qingxun.core.system.service.SysConfigService;


/**
 * 基础控制器 
 * 其他控制器继承此控制器获得日期字段类型转换和防止XSS攻击的功能
 * @description 
 * @author leo
 * @date 2014年3月19日
 */
@Controller
@RequestMapping("rest/upload")
public class UploadController {
	@Autowired
	protected SysConfigService sysConfigService;
	protected SysConfig resConfig;
	protected Log log=LogFactory.getLog(this.getClass());

	/**
	 * 默认页面
	 */
	@RequestMapping(method = RequestMethod.GET)
	public String uploadFile() {
		return "system/uploadFile";
	}
	/**
	 * 上传文件
	 * @param storePath 上传路径Key
	 * @param prefixList 保存前缀
	 * @return fileList
	 * @throws IOException 
	 * @throws IllegalStateException 
	 * */
	@RequestMapping(value = "up", method = RequestMethod.POST)
	@ResponseBody
	public String upload(HttpServletRequest request){
		//返回保存的文件
//		List<String> upFilePathList=new ArrayList<String>();
		String resultStr="";
		try {
			//获取图片设置路径
			SysConfig baseConfig=sysConfigService.getEntityDao()
					.findUnique("from SysConfig s where key_=?0", "base.store.path");
			//健康档案列表,创建一个通用的多部分解析器
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
			//判断 request 是否有文件上传,即多部分请求
			if(multipartResolver.isMultipart(request)){
				//转换成多部分request  
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
				//取得request中的所有文件名
				Iterator<String> iter = multiRequest.getFileNames();
				boolean flag=true;
				log.info("size------------------"+multiRequest.getFileNames());
				while(iter.hasNext()){
					//记录上传过程起始时的时间，用来计算上传时间
					long pre = System.nanoTime();
					//取得上传文件
					MultipartFile file = multiRequest.getFile(iter.next());
					log.info("file---------------"+file.getName());
					if(file != null){
						//取得当前上传文件的文件名称
						String myFileName = file.getOriginalFilename();
						String fileType=myFileName.substring(myFileName.indexOf("."));
						//如果名称不为“”,说明该文件存在，否则说明该文件不存在
						if(myFileName.trim() !=""){
							log.debug("文件名:"+myFileName);
							//定义上传路径
							String path = baseConfig.getVal()+"/"+pre+fileType;
							File localFile = new File(path);
							log.info("上传到:"+path);
							file.transferTo(localFile);
//							upFilePathList.add("/"+pre+fileType);
							if(flag){
								resultStr+=pre+fileType;
								flag=false;
							}else{
								resultStr+=","+pre+fileType;
							}
						}
					}
					//记录上传该文件后的时间
					int finaltime = (int) System.currentTimeMillis();
					log.debug("共用时:"+(finaltime - pre)+"毫秒");
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 		
		return resultStr;
	}	
	
	/**
	 * 上传文件
	 * @param storePath 上传路径Key
	 * @param prefixList 保存前缀
	 * @return fileList
	 * @throws IOException 
	 * @throws IllegalStateException 
	 * */
	@RequestMapping(value = "upforJson", method = RequestMethod.POST)
	@ResponseBody
	public ResultMsg<String> uploadForJson(HttpServletRequest request){
		//返回保存的文件
//		List<String> upFilePathList=new ArrayList<String>();
		String resultStr="";
		ResultMsg<String> result=new ResultMsg<String>();
		try {
			//获取图片设置路径
			SysConfig baseConfig=sysConfigService.getEntityDao()
					.findUnique("from SysConfig s where key_=?0", "base.store.path");
			//健康档案列表,创建一个通用的多部分解析器
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
			//判断 request 是否有文件上传,即多部分请求
			if(multipartResolver.isMultipart(request)){
				//转换成多部分request  
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
				//取得request中的所有文件名
				Iterator<String> iter = multiRequest.getFileNames();
				boolean flag=true;
				log.info("size------------------"+multiRequest.getFileNames());
				while(iter.hasNext()){
					//记录上传过程起始时的时间，用来计算上传时间
					long pre = System.nanoTime();
					//取得上传文件
					MultipartFile file = multiRequest.getFile(iter.next());
					log.info("file---------------"+file.getName());
					if(file != null){
						//取得当前上传文件的文件名称
						String myFileName = file.getOriginalFilename();
						String fileType=myFileName.substring(myFileName.indexOf("."));
						//如果名称不为“”,说明该文件存在，否则说明该文件不存在
						if(myFileName.trim() !=""){
							log.debug("文件名:"+myFileName);
							//定义上传路径
							String path = baseConfig.getVal()+"/"+pre+fileType;
							File localFile = new File(path);
							log.info("上传到:"+path);
							file.transferTo(localFile);
//							upFilePathList.add("/"+pre+fileType);
							if(flag){
								resultStr+=pre+fileType;
								flag=false;
							}else{
								resultStr+=","+pre+fileType;
							}
						}
					}
					//记录上传该文件后的时间
					int finaltime = (int) System.currentTimeMillis();
					log.debug("共用时:"+(finaltime - pre)+"毫秒");
				}
				result.setCode(ResultMsg.RespCode.SUCCESS.value);
				result.setData(resultStr);
				return result;
			}
			result.setCode(ResultMsg.RespCode.FAILED.value);
			result.setMsg("上传文件为空！");			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result.setCode(ResultMsg.RespCode.EXCEPTION.value);
			result.setMsg(e.getMessage());
		} 		
		return result;
	}		
	/**
	 * 用来获取当前登录用户
	 * @return 当前登录用户
	 */
	public User getCurUser() {
		
		//Object = null;
		User curUser = (User) SecurityUtils.getSubject().getPrincipal();
		return curUser;
	}
	
	/**
	 * 上传文件
	 * @param storePath 上传路径Key
	 * @param prefixList 保存前缀
	 * @return fileList
	 * @throws IOException 
	 * @throws IllegalStateException 
	 * */
	@RequestMapping(value = "upforJsonFullPath", method = RequestMethod.POST)
	@ResponseBody
	public ResultMsg<String> upforJsonFullPath(HttpServletRequest request){
		//返回保存的文件
//		List<String> upFilePathList=new ArrayList<String>();
		String resultStr="";
		ResultMsg<String> result=new ResultMsg<String>();
		try {
			//获取图片设置路径
			SysConfig baseConfig=sysConfigService.getEntityDao()
					.findUnique("from SysConfig s where key_=?0", "base.store.path");
			//资源路径
			SysConfig resConfig=sysConfigService.getEntityDao()
					.findUnique("from SysConfig s where key_=?0", "res.http.path");
			//健康档案列表,创建一个通用的多部分解析器
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
			//判断 request 是否有文件上传,即多部分请求
			if(multipartResolver.isMultipart(request)){
				//转换成多部分request  
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
				//取得request中的所有文件名
				Iterator<String> iter = multiRequest.getFileNames();
				boolean flag=true;
				log.info("size------------------"+multiRequest.getFileNames());
				while(iter.hasNext()){
					//记录上传过程起始时的时间，用来计算上传时间
					long pre = System.nanoTime();
					//取得上传文件
					MultipartFile file = multiRequest.getFile(iter.next());
					log.info("file---------------"+file.getName());
					if(file != null){
						//取得当前上传文件的文件名称
						String myFileName = file.getOriginalFilename();
						String fileType=myFileName.substring(myFileName.indexOf("."));
						//如果名称不为“”,说明该文件存在，否则说明该文件不存在
						if(myFileName.trim() !=""){
							log.debug("文件名:"+myFileName);
							//定义上传路径
							String path = baseConfig.getVal()+"/"+pre+fileType;
							File localFile = new File(path);
							log.info("上传到:"+path);
							file.transferTo(localFile);
//							upFilePathList.add("/"+pre+fileType);
							if(flag){
								resultStr+=resConfig.getVal()+"/"+pre+fileType;
								flag=false;
							}else{
								resultStr+=","+resConfig.getVal()+"/"+pre+fileType;
							}
						}
					}
					//记录上传该文件后的时间
					int finaltime = (int) System.currentTimeMillis();
					log.debug("共用时:"+(finaltime - pre)+"毫秒");
				}
				result.setCode(ResultMsg.RespCode.SUCCESS.value);
				result.setData(resultStr);
				return result;
			}
			result.setCode(ResultMsg.RespCode.FAILED.value);
			result.setMsg("上传文件为空！");			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result.setCode(ResultMsg.RespCode.EXCEPTION.value);
			result.setMsg(e.getMessage());
		} 		
		return result;
	}		
	
	
}
